<template>
  <view class="checkout-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <view class="left" @click="goBack">
          <wd-icon name="arrow-left" size="36rpx" />
        </view>
        <view class="center">
          <view class="tab-group">
            <view class="tab-item" :class="{ active: deliveryType === 'delivery' }"
              @click="switchDeliveryType('delivery')">
              配送
            </view>
            <view class="tab-item" :class="{ active: deliveryType === 'self' }" @click="switchDeliveryType('self')">
              自提
            </view>
          </view>
        </view>
        <view class="right"></view>
      </view>
    </view>

    <!-- 页面内容向下偏移 -->
    <view class="page-content" :style="{ paddingTop: navigationBarHeight + 'px' }">
      <!-- 配送地址/自提门店 -->
      <view class="address-card" @tap="handleAddressClick">
        <!-- 配送地址 -->
        <template v-if="deliveryType === 'delivery'">
          <view v-if="address" class="address-info">
            <view class="address-main">
              <view class="address-detail">
                <wd-icon name="location" size="32rpx" custom-class="location-icon" />
                <text class="address-text">{{ address.fullAddress }}</text>
              </view>
              <view class="user-info">
                <text class="name">{{ address.name }}</text>
                <text class="phone">{{ address.phone }}</text>
              </view>
            </view>
            <wd-icon name="arrow-right" custom-class="arrow-icon" />
          </view>
          <view v-else class="no-address">
            <text>请选择收货地址</text>
            <wd-icon name="arrow-right" custom-class="arrow-icon" />
          </view>
        </template>

        <!-- 自提门店 -->
        <template v-else>
          <view v-if="selectedStore" class="store-info">
            <view class="store-main">
              <view class="store-detail">
                <wd-icon name="shop" size="32rpx" custom-class="store-icon" />
                <text class="store-text">{{ selectedStore.name }}</text>
              </view>
              <view class="store-sub-info">
                <view class="store-address">{{ selectedStore.fullAddress }}</view>
                <view class="store-phone">电话：{{ selectedStore.phone }}</view>
                <view class="store-time">营业时间：{{ selectedStore.openingHours }}</view>
              </view>
            </view>
            <wd-icon name="arrow-right" custom-class="arrow-icon" />
          </view>
          <view v-else class="no-address">
            <text>请选择自提门店</text>
            <wd-icon name="arrow-right" custom-class="arrow-icon" />
          </view>
        </template>
      </view>

      <!-- 商品列表 -->
      <view class="goods-card">
        <view v-for="item in orderItems" :key="item.id" class="goods-item">
          <image :src="item.image" mode="aspectFill" class="goods-image" />
          <view class="goods-info">
            <view class="goods-name">{{ item.name }}</view>
            <view class="goods-params" v-if="item.params">{{ item.params }}</view>
            <view class="price-quantity">
              <view class="price-wrapper">
                <text class="price">¥{{ formatPrice(item.afterCouponPrice || item.price) }}</text>
                <text v-if="item.afterCouponPrice && item.afterCouponPrice !== item.price" class="original-price">¥{{
                  formatPrice(item.price) }}</text>
              </view>
              <text class="quantity">x{{ item.quantity }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="order-card">
        <view class="info-item">
          <text>商品总价</text>
          <text class="price">¥{{ formatPrice(totalPrice) }}</text>
        </view>
        <view class="info-item discount-item" v-if="discountAmount > 0">
          <view class="discount-info">
            <text>优惠金额</text>
            <text v-if="selectedCoupon?.discountType === 2" class="discount-desc">
              ({{ formatPrice(selectedCoupon.discountAmount) }}折)
            </text>
            <text v-else-if="selectedCoupon?.discountType === 1" class="discount-desc">
              (满{{ formatPrice(selectedCoupon.minPurchaseAmount) }}减{{ formatPrice(selectedCoupon.discountAmount) }})
            </text>
          </view>
          <text class="discount-price">-¥{{ formatPrice(discountAmount) }}</text>
        </view>
        <view class="info-item" v-if="deliveryType === 'delivery'">
          <text>运费</text>
          <text class="price">¥{{ formatPrice(shipping) }}</text>
        </view>
        <view class="info-item">
          <text>优惠券</text>
          <view class="coupon-select" @click="showCouponPopup">
            <template v-if="deliveryType === 'delivery' && !address">
              <text class="hint-text">请先选择收货地址</text>
              <wd-icon name="arrow-right" custom-class="arrow-icon" />
            </template>
            <template v-else-if="deliveryType === 'self' && !selectedStore">
              <text class="hint-text">请先选择自提门店</text>
              <wd-icon name="arrow-right" custom-class="arrow-icon" />
            </template>
            <template v-else>
              <text style="color: #FF2C54;">{{ selectedCoupon ? selectedCoupon.name : '未使用' }}</text>
              <wd-icon name="arrow-right" custom-class="arrow-icon" />
            </template>
          </view>
        </view>
        <view class="info-item">
          <text>支付方式</text>
          <view class="payment-info">
            <image src="/static/images/payment/wechat.png" mode="aspectFit" class="payment-icon" />
            <text>微信支付</text>
          </view>
        </view>
      </view>

      <!-- 底部结算栏 -->
      <view class="checkout-bar">
        <wd-button block type="primary" @click="submitOrder" custom-style="background: #FF2C54; border-color: #FF2C54;">
          立即支付 ¥{{ formatPrice(finalPrice) }}
        </wd-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { getOrderCouponPrice, createOrder, orderPaySuccess } from '@/api/order'
import { formatPrice } from '@/utils/format'

// 状态栏和导航栏高度
const statusBarHeight = ref(0)
const navigationBarHeight = ref(0)

// 配送方式
const deliveryType = ref('delivery') // 默认配送

// 地址和门店数据
const address = ref(null)
const selectedStore = ref(null)

// 订单数据
const orderItems = ref([])  // 初始化为空数组
const totalPrice = ref(0)   // 原始总价

// 优惠券相关
const shipping = ref(0)
const selectedCoupon = ref(null)

// 是否从购物车过来
const cart = ref(false)

// 计算属性
const discountAmount = computed(() => {
  if (!selectedCoupon.value || !selectedCoupon.value.afterCouponOrderAmount) {
    return 0
  }
  // 计算优惠金额：原价 - 优惠后价格
  const discount = totalPrice.value - selectedCoupon.value.afterCouponOrderAmount
  // 确保优惠金额为正数
  return Number(Math.abs(discount).toFixed(2))
})

const finalPrice = computed(() => {
  let price = totalPrice.value || 0

  // 加上运费（如果是配送方式）
  if (deliveryType.value === 'delivery') {
    price += shipping.value || 0
  }

  // 如果有优惠券，使用优惠后的价格
  if (selectedCoupon.value && selectedCoupon.value.afterCouponOrderAmount !== undefined) {
    // 优惠后的价格加上运费（如果是配送方式）
    price = selectedCoupon.value.afterCouponOrderAmount +
      (deliveryType.value === 'delivery' ? shipping.value || 0 : 0)
  }

  // 确保返回两位小数的字符串
  return Number(price).toFixed(2)
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const switchDeliveryType = (type) => {
  deliveryType.value = type
  // 切换时清空另一种方式的选择
  if (type === 'delivery') {
    selectedStore.value = null
  } else {
    address.value = null
  }
}

const handleAddressClick = () => {
  if (deliveryType.value === 'delivery') {
    goToAddressList()
  } else {
    goToStoreList()
  }
}

const goToAddressList = () => {
  try {
    uni.navigateTo({
      url: '/pages/address/list'
    })
  } catch (error) {
    console.error('导航异常:', error)
    uni.showToast({
      title: '页面跳转失败',
      icon: 'none'
    })
  }
}

const goToStoreList = () => {
  try {
    uni.navigateTo({
      url: '/pages/store/list',
      fail: (err) => {
        console.error('导航失败:', err)
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  } catch (error) {
    console.error('导航异常:', error)
  }
}

const showCouponPopup = () => {
  if (deliveryType.value === 'delivery' && !address.value) {
    goToAddressList()
    return
  }

  if (deliveryType.value === 'self' && !selectedStore.value) {
    goToStoreList()
    return
  }

  let url = `/pages/coupon/select?orderAmount=${totalPrice.value}`
  if (selectedCoupon.value != null) {
    url += `&selectedCouponId=${selectedCoupon.value.id}`
  }

  // 修改为跳转到优惠券选择页面
  uni.navigateTo({
    url
  })
}

const submitOrder = async () => {
  if (deliveryType.value === 'delivery' && !address.value) {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none'
    })
    return
  }

  if (deliveryType.value === 'self' && !selectedStore.value) {
    uni.showToast({
      title: '请选择自提门店',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({
      title: '提交订单中'
    })

    // 构建订单参数
    const orderParams = {
      cart: cart.value,
      userAddressId: deliveryType.value === 'delivery' ? address.value.id : null,
      username: deliveryType.value === 'delivery' ? address.value.name : selectedStore.value.contactName,
      couponId: selectedCoupon.value?.id || null,
      couponName: selectedCoupon.value?.name || null,
      realAmount: Number(finalPrice.value),
      totalAmount: totalPrice.value,
      remark: '', // 如果需要备注功能可以添加
      pickup: deliveryType.value === 'self' ? 1 : 0,
      pickupPointId: deliveryType.value === 'self' ? selectedStore.value.id : null,
      pickupPointName: deliveryType.value === 'self' ? selectedStore.value.name : null,
      orderItemList: orderItems.value.map(item => ({
        productId: item.id,
        productName: item.name,
        quantity: item.quantity,
        realPrice: item.afterCouponPrice || item.price,
        price: item.price
      }))
    }

    // 调用创建订单接口
    const result = await createOrder(orderParams)

    // 发起微信支付
    try {
      console.log('result', result)
      await new Promise((resolve, reject) => {
        uni.requestPayment({
          provider: 'wxpay',
          timeStamp: result.timeStamp,
          nonceStr: result.nonceStr,
          package: result.prepayPackage,
          signType: result.signType,
          paySign: result.paySign,
          success: (res) => {
            resolve(res)
          },
          fail: (err) => {
            reject(err)
          }
        })
      })

      // 支付成功
      uni.showToast({
        title: '支付成功',
        icon: 'success'
      })

      // 支付成功 往向后端发送请求 提醒支付成功 （目前后端没有上线 回调接口是不能被回调的（不在公网））
      await orderPaySuccess(result.orderId)

      // 跳转到支付成功页面
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/order/success?orderId=${result.orderId}&orderNo=${result.orderNo}&amount=${finalPrice.value}`
        })
      }, 1500)

    } catch (payError) {
      // 支付失败或取消
      console.error('支付失败:', payError)
      // 支付成功
      uni.showToast({
        title: '支付失败',
        icon: 'error'
      })
      // 跳转到订单详情页
      uni.redirectTo({
        url: `/pages/order/detail?orderId=${result.orderId}`
      })
    }

  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: error.message || '下单失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 修改生命周期钩子
onMounted(() => {
  // 获取系统信息设置状态栏高度
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight
  navigationBarHeight.value = statusBarHeight.value + 44
})

// 修改 onLoad 生命周期
onLoad((options) => {
  // 监听地址选择事件
  uni.$on('updateAddress', (newAddress) => {
    address.value = newAddress
  })

  uni.$on('updateStore', (store) => {
    selectedStore.value = store
  })
  cart.value = options.cart
  console.log('cart.value', cart.value)
  // 接收购物车传递的商品数据
  if (options.cartItems) {
    try {
      const goToJson = JSON.parse(decodeURIComponent(options.cartItems))
      orderItems.value = goToJson.checkoutItems.map(item => ({
        id: item.id,
        name: item.name,
        price: Number(item.price),
        quantity: Number(item.quantity),
        image: item.image
      }))

      // 计算原始总价
      totalPrice.value = Number(goToJson.totalPrice)
    } catch (error) {
      console.error('解析购物车数据失败:', error)
      uni.showToast({
        title: '数据加载失败',
        icon: 'none'
      })
    }
  }

  // 修改优惠券选择监听
  uni.$on('updateCoupon', async (coupon) => {
    // 如果选择了优惠券，请求新的价格
    if (coupon) {
      try {
        // 构建请求参数
        const requestData = {
          couponId: coupon.id,
          productList: orderItems.value.map(item => ({
            id: item.id,
            count: item.quantity
          })),
          amount: totalPrice.value
        }

        // 发送请求获取优惠后价格
        const data = await getOrderCouponPrice(requestData)

        // 更新商品价格和总价
        if (data) {
          // 保存优惠后的价格到优惠券对象中
          selectedCoupon.value = {
            ...coupon,
            afterCouponOrderAmount: data.afterCouponOrderAmount
          }
          // 更新商品单价
          const updatedPrices = data.productList
          orderItems.value = orderItems.value.map(item => {
            const updatedItem = updatedPrices.find(p => p.id === item.id)
            if (updatedItem) {
              return {
                ...item,
                afterCouponPrice: updatedItem.afterCouponPrice
              }
            }
            return item
          })
        }
      } catch (error) {
        console.error('获取优惠价格失败:', error)
        uni.showToast({
          title: '获取优惠价格失败',
          icon: 'none'
        })
      }
    } else {
      // 取消选择优惠券，清空相关数据
      selectedCoupon.value = null
      orderItems.value = orderItems.value.map(item => ({
        ...item,
        afterCouponPrice: null
      }))
    }
  })
})

// 将事件注销移到 onUnload
onUnload(() => {
  uni.$off('updateAddress')
  uni.$off('updateStore')
  uni.$off('updateCoupon')
})
</script>

<style lang="scss">
.checkout-container {
  min-height: 100vh;
  background: #f8f8f8;

  .custom-navbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background: #fff;
    z-index: 999;

    .navbar-content {
      height: 44px;
      display: flex;
      align-items: center;
      padding: 0 30rpx;

      .left {
        width: 80rpx;
        display: flex;
        align-items: center;

        :deep(.wd-icon) {
          color: #333;
        }
      }

      .center {
        flex: 1;
        display: flex;
        justify-content: center;

        .tab-group {
          display: flex;
          background: #F5F5F5;
          border-radius: 32rpx;
          padding: 4rpx;

          .tab-item {
            padding: 12rpx 40rpx;
            font-size: 28rpx;
            color: #666;
            border-radius: 28rpx;
            transition: all 0.3s;

            &.active {
              background: #fff;
              color: #333;
              font-weight: 500;
              box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
            }
          }
        }
      }

      .right {
        width: 80rpx;
      }
    }
  }

  .page-content {
    padding-bottom: 120rpx;
  }
}

.address-card {
  background: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;

  .address-info {
    display: flex;
    align-items: center;

    .address-main {
      flex: 1;

      .address-detail {
        display: flex;
        align-items: flex-start;
        font-size: 30rpx;
        color: #333;
        line-height: 1.4;
        margin-bottom: 12rpx;

        :deep(.location-icon) {
          flex-shrink: 0;
          margin-right: 10rpx;
          margin-top: 4rpx;
          color: #666;
        }

        .address-text {
          flex: 1;
        }
      }

      .user-info {
        font-size: 26rpx;
        color: #666;
        padding-left: 42rpx;

        .name {
          margin-right: 20rpx;
        }
      }
    }
  }

  .no-address {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #666;
  }
}

.goods-card {
  background: #fff;
  margin: 20rpx;
  padding: 20rpx;
  border-radius: 16rpx;

  .goods-item {
    display: flex;
    padding: 20rpx 0;
    position: relative;

    &:not(:last-child) {
      border-bottom: 1rpx solid #eee;
    }

    .goods-image {
      width: 180rpx;
      height: 180rpx;
      border-radius: 12rpx;
      background: #f5f5f5;
      flex-shrink: 0;
    }

    .goods-info {
      flex: 1;
      margin-left: 24rpx;
      display: flex;
      flex-direction: column;
      height: 180rpx;
      position: relative;

      .goods-name {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        line-height: 1.4;
        margin-bottom: 12rpx;
        // 文本超出两行显示省略号
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .goods-params {
        font-size: 24rpx;
        color: #999;
        line-height: 1.4;
        // 文本超出一行显示省略号
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .price-quantity {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .price-wrapper {
          display: flex;
          align-items: baseline;
          gap: 8rpx;

          .price {
            font-size: 32rpx;
            color: #ff2c54;
            font-weight: bold;
          }

          .original-price {
            font-size: 24rpx;
            color: #999;
            text-decoration: line-through;
          }
        }

        .quantity {
          font-size: 26rpx;
          color: #666;
        }
      }
    }
  }
}

.order-card {
  background: #fff;
  margin: 20rpx;
  padding: 20rpx 30rpx;
  border-radius: 16rpx;

  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    font-size: 28rpx;

    .price {
      color: #ff2c54;
    }

    .coupon-select {
      display: flex;
      align-items: center;
      color: #666;

      .hint-text {
        color: #ff6b81;
        font-size: 26rpx;
      }

      :deep(.arrow-icon) {
        margin-left: 10rpx;
        color: #999;
      }
    }
  }

  .discount-item {
    .discount-info {
      display: flex;
      align-items: center;
      gap: 8rpx;

      .discount-desc {
        font-size: 24rpx;
        color: #666;
      }
    }

    .discount-price {
      color: #ff2c54;
      font-weight: 500;
    }
  }
}

.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.payment-info {
  display: flex;
  align-items: center;
  gap: 12rpx;

  .payment-icon {
    width: 36rpx;
    height: 36rpx;
  }

  text {
    font-size: 28rpx;
    color: #333;
  }
}

// 添加门店相关样式
.store-info {
  display: flex;
  align-items: flex-start;

  .store-main {
    flex: 1;

    .store-detail {
      display: flex;
      align-items: flex-start;
      font-size: 30rpx;
      color: #333;
      line-height: 1.4;
      margin-bottom: 12rpx;

      :deep(.store-icon) {
        flex-shrink: 0;
        margin-right: 10rpx;
        margin-top: 4rpx;
        color: #666;
      }

      .store-text {
        flex: 1;
        font-weight: 500;
      }
    }

    .store-sub-info {
      padding-left: 42rpx;

      .store-address,
      .store-phone,
      .store-time {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 8rpx;
        line-height: 1.4;
      }
    }
  }
}

.hint-text {
  color: #999;
  margin-right: 10rpx;
}
</style>